package com.yungu.swift.monitor.utils;

import org.hyperic.sigar.Sigar;
import org.springframework.util.StringUtils;

import java.io.*;
import java.util.Set;

/**
 * @author : cuixiuyin
 * @date : 2019/10/12
 */
public class SigarUtil {

    private static final String winDllFile = "sigar-amd64-winnt.dll";
    private static final String linuxDllFile = "libsigar-amd64-linux.so,libsigar-x86-linux.so,sigar-x86-winnt.dll";

    static {
        String osName = System.getProperty("os.name").toLowerCase();
        String property = System.getProperty("java.library.path");
        String path = osName.contains("linux") ? property.split("\\:")[1] : property.split("\\;")[0];
        String dllFiles = osName.contains("linux") ? linuxDllFile : winDllFile;
        Set<String> toSet = StringUtils.commaDelimitedListToSet(dllFiles);
        for (String dllFile : toSet) {
            // 得到输出流
            File file = new File(path + File.separator + dllFile);
            if (!file.exists()) {
                try {
                    file.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            try (OutputStream out = new FileOutputStream(file);
                 InputStream in = SigarUtil.class.getClassLoader().getResourceAsStream(dllFile)) {
                int i;//从输入流读取一定数量的字节，返回 0 到 255 范围内的 int 型字节值
                while ((i = in.read()) != -1) {
                    out.write(i);
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static Sigar getSigar() {
        return new Sigar();
    }
}
